﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;

using ECCIT;
using ECCIT.Data;
using ECCIT.Business.DAL;

using OgilvyOne.Utility;
using OgilvyOne.UKNow.Common;
using OgilvyOne.UKNow.Globalization;
using OgilvyOne.UKNow.Utility;
using OgilvyOne.UKNow.Model;
using OgilvyOne.UKNow.IDAL;

namespace OgilvyOne.UKNow.DAL
{
    public class EventsPhoneImageDAL : UKNowBaseDAL, IDALEventsPhoneImage
    {
        private const string TBL_NAME = "UKNOW_EVENTS_PHONE_IMAGE";
        private const string COL_LANG_ID            = "COL_LANG_ID";
        private const string COL_IMAGE_ID            = "COL_IMAGE_ID";
        private const string COL_EVENTS_ID         = "COL_EVENTS_ID";
        private const string COL_IMAGE_NAME         = "COL_IMAGE_NAME";
        private const string COL_IMAGE_PATH          = "COL_IMAGE_PATH";

        private const string COL_IMAGE_THUMB_PATH = "COL_IMAGE_THUMB_PATH";
 
        //private const string COL_EVENTS_IMAGE_AVATAR = "COL_EVENTS_IMAGE_AVATAR";
        private const string COL_IMAGE_EXT = "COL_IMAGE_EXT";
        private const string COL_IMAGE_DESC    = "COL_IMAGE_DESC";
        private const string COL_IMAGE_TAG = "COL_IMAGE_TAG";
        private const string COL_IMAGE_STATE = "COL_IMAGE_STATE";
        private const string COL_IMAGE_ORDER      = "COL_IMAGE_ORDER";
        private const string COL_IMAGE_RECO      = "COL_IMAGE_RECO";
        private const string COL_IMAGE_INSERT_TIME = "COL_IMAGE_INSERT_TIME";
        private const string COL_IMAGE_UPDATE_TIME = "COL_IMAGE_UPDATE_TIME";

        public override string TableName { get { return TBL_NAME; } }

        public override Type ModelType { get { return typeof(EventsImageModel); } }

        [PrimaryKey]
        public IField LanguageID { get { return FieldFactory.Create(ModelType, "LanguageID", ColumnFactory.CreateColumn(COL_LANG_ID, DataType.Int)); } }
        [PrimaryKey]
        public IField ID { get { return FieldFactory.Create(ModelType, "ID", ColumnFactory.CreateColumn(COL_IMAGE_ID, DataType.Int)); } }
        public IField EventsID { get { return FieldFactory.Create(ModelType, "EventsID", ColumnFactory.CreateColumn(COL_EVENTS_ID, DataType.Int)); } }
        public IField Name { get { return FieldFactory.Create(ModelType, "Name", ColumnFactory.CreateColumn(COL_IMAGE_NAME, DataType.String, 200)); } }
        public IField Path { get { return FieldFactory.Create(ModelType, "Path", ColumnFactory.CreateColumn(COL_IMAGE_PATH, DataType.String, 200)); } }
        //mff
        public IField Path1 { get { return FieldFactory.Create(ModelType, "Path1", ColumnFactory.CreateColumn(COL_IMAGE_THUMB_PATH, DataType.String, 200)); } }
        //mff
        //public IField Avatar { get { return FieldFactory.Create(ModelType, "Avatar", ColumnFactory.CreateColumn(COL_EVENTS_IMAGE_AVATAR, DataType.String, 200)); } }
        public IField Extension { get { return FieldFactory.Create(ModelType, "Extension", ColumnFactory.CreateColumn(COL_IMAGE_EXT, DataType.String, 20)); } }
        public IField Description { get { return FieldFactory.Create(ModelType, "Description", ColumnFactory.CreateColumn(COL_IMAGE_DESC, DataType.String, 500)); } }
        public IField Tag { get { return FieldFactory.Create(ModelType, "Tag", ColumnFactory.CreateColumn(COL_IMAGE_TAG, DataType.String, 200)); } }
        public IField State { get { return FieldFactory.Create(ModelType, "State", ColumnFactory.CreateColumn(COL_IMAGE_STATE, DataType.Int)); } }
        public IField Order { get { return FieldFactory.Create(ModelType, "Order", ColumnFactory.CreateColumn(COL_IMAGE_ORDER, DataType.Int)); } }
        public IField IsRecommendation { get { return FieldFactory.Create(ModelType, "IsRecommendation", ColumnFactory.CreateColumn(COL_IMAGE_RECO, DataType.Bit)); } }
        public IField InsertedTime { get { return FieldFactory.Create(ModelType, "InsertedTime", ColumnFactory.CreateColumn(COL_IMAGE_INSERT_TIME, DataType.DateTime)); } }
        public IField UpdatedTime { get { return FieldFactory.Create(ModelType, "UpdatedTime", ColumnFactory.CreateColumn(COL_IMAGE_UPDATE_TIME, DataType.DateTime)); } }
        //mff
        public override IField[] InsertFields { get { return new IField[] { LanguageID, ID, EventsID, Name, Path, Path1, Extension, Description, Tag, State, Order, IsRecommendation, InsertedTime, UpdatedTime }; } }
        public override IField[] SelectFields { get { return InsertFields; } }
        //mff
        public override IField[] UpdateFields { get { return new IField[] { LanguageID, ID, EventsID, Name, Path, Path1, Extension, Description, Tag, State, Order, IsRecommendation, UpdatedTime }; } }

        public EventsPhoneImageDAL() { }

        public EventsPhoneImageDAL(LanguageType languageType) { this.Language = LanguageFactory.Create(languageType); }

        private void SetForeignKeyModel(EventsImageModel model)
        {
            if (model == null) return;
            //model.FileType = 1;
            model.ThumbnailImagePath = model.Path1;
            model.Events = new EventsDAL(this.Language.LanguageType).GetEventsModelByID(model.EventsID);
        }

        #region IDALEventsImage Members

        public EventsImageModel GetEventsPhoneImageModelByID(int? id)
        {
            EventsImageModel model = (EventsImageModel)GetModelByPrimaryKey(this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });
            SetForeignKeyModel(model);
            return model;
        }

        public IList<EventsImageModel> GetAllEventsPhoneImageModels(int? eventsID)
        {
            IDataParameter[] parms = DBHelper.GetDataParameters(new IField[] { EventsID, LanguageID });
            parms[0].Value = eventsID;
            parms[1].Value = (int)this.Language.LanguageType;

            string whereClause = "WHERE " + COL_EVENTS_ID + "=#" + COL_EVENTS_ID + " AND " + COL_LANG_ID + "=#" + COL_LANG_ID;

            IList<EventsImageModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc)), parms).List.Cast<EventsImageModel>().ToList();
            foreach (EventsImageModel model in models)
                SetForeignKeyModel(model);

            return models;
        }
        public Dictionary<string, string> getNameurl(int? eid)
        {
            string sql = String.Format("select COL_IMAGE_NAME as name, COL_IMAGE_PATH as url  from {0} where {1}={2}", TBL_NAME, COL_EVENTS_ID,eid.ToString());
            DataSet ds = DBHelper.ExecuteDataSet(sql, null);
            DataTable dt=ds.Tables[0];
            if (dt.Rows.Count > 0)
            {
                Dictionary<string, string> dir = new Dictionary<string, string>();
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["url"] != DBNull.Value && dr["url"].ToString() != string.Empty && !dir.ContainsKey(dr["url"].ToString()))
                        dir.Add(dr["url"].ToString(), dr["name"].ToString());
                }
                return dir;
            }
            else
            {
                return null;
            }

        }

        /// <summary>
        /// 获取活动对应的手机图片
        /// </summary>
        /// <param name="eid">活动ID</param>
        /// <returns></returns>
        public IList<PhoneImage>  GetEventPhoneImages(int? eid)
        {
            if (!eid.HasValue)
                return null;
            string sql =
                string.Format(
                    "select COL_IMAGE_NAME as Imagename, COL_IMAGE_PATH as Imagpath,COL_IMAGE_THUMB_PATH as Thumbpath  from {0} where {1}={2} and COL_IMAGE_STATE=1 and COL_LANG_ID={3}",
                    TBL_NAME, COL_EVENTS_ID, eid,(int)this.Language.LanguageType);
            DataSet ds = DBHelper.ExecuteDataSet(sql, null);
            if(ds!=null&&ds.Tables.Count>0&&ds.Tables[0]!=null&&ds.Tables[0].Rows.Count>0)
            {
                return ds.Tables[0].ToList<PhoneImage>();
            }
            return null;

        }

        /*
         * 代码修改：
         * 修改人员：穆凤凤
         * 修改日期：2012-04-21
         * 修改原因：原先根据关键字查找图片仅仅是对关键字做了like，应该有更复杂的处理
         * */
        public PagingList GetEventsPhoneImageModelsByKeywords(string keywordString, PagingParameter pagingParams)
        {
            JoinedString keywords = new JoinedString(keywordString, " ");
            StringBuilder highLevelBuilder = new StringBuilder();
            StringBuilder lowLevelBuilder = new StringBuilder();
            foreach (string keyword in keywords)
            {
                if (string.IsNullOrEmpty(keyword)) continue;
                if (highLevelBuilder.Length > 0)
                    highLevelBuilder.Append(" and ");
                highLevelBuilder.AppendFormat(" {0} like '%{1}%' ", COL_IMAGE_TAG, keyword);

                if (lowLevelBuilder.Length > 0)
                    lowLevelBuilder.Append(" or ");
                lowLevelBuilder.AppendFormat(" ({0} like '%{1}%') ", COL_IMAGE_TAG, keyword);
            }

            string whereClause = string.Format("where {0}={1} and {2}={3} ", COL_IMAGE_STATE, 1, COL_LANG_ID, (int)this.Language.LanguageType);
            if (highLevelBuilder.Length > 0)
                whereClause += " and ((" + highLevelBuilder.ToString() + ") or " + lowLevelBuilder.ToString() + ")";
            IList<EventsImageModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsImageModel>().ToList();

            List<MediaFileModel> lmm = new List<MediaFileModel>();
            MediaFileModel mfm = null;
            List<string> imageNames = new List<string>();
            EventsDAL dal = new EventsDAL(this.Language.LanguageType);
            EventsModel eventsModel = null;
            foreach (EventsImageModel eim in models)
            {
                mfm = new MediaFileModel();
                mfm.ID = eim.ID;
                mfm.LanguageID = eim.LanguageID;
                mfm.Name = eim.Name;
                mfm.Path = eim.Path1;
                mfm.MediType = 0;//活动图片

                // 对于同名的图片，只显示一个搜索结果
                if (!imageNames.Contains(eim.Path1))
                {
                    eventsModel = dal.GetEventsModelByID(eim.EventsID);
                    if (eventsModel == null) continue;
                    mfm.HtmlFileName = (string.IsNullOrEmpty(eventsModel.HtmlFileName)) ? eventsModel.ID + ".html" : eventsModel.HtmlFileName;
                    lmm.Add(mfm);
                    imageNames.Add(eim.Path1);
                    mfm = null;
                }
            }

            PageTools page = new PageTools(lmm, pagingParams.CurrentPageIndex+1, pagingParams.PageSize);

            return new PagingList(page.DataList, lmm.Count);
        }

        public IList<EventsImageModel> GetPublishedEventsImageModels(int? eventsID)
        {
            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_IMAGE_STATE, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_ID, eventsID, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));
            /*
             * 代码修改：
             * 修改人员：刘扬
             * 修改日期：2012-04-08
             * 修改原因：原先图片的是否推荐标志位现用于是否在Gallery显示，所以获取发布状态图片需要增加过滤条件
             * */
            //builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_IMAGE_RECO, 0, SearchConditionOperator.Equals));
            
            string whereClause = builder.ToSqlCommand();
            IList<EventsImageModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(Order.PropertyName + "," + UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsImageModel>().ToList();
            
            foreach (EventsImageModel model in models)
                SetForeignKeyModel(model);
            return models;
        }
        /*
            * 代码修改：
            * 修改人员：穆凤凤
            * 修改日期：2012-04-10
            * 修改原因：当某一活动设置为未发布时,其相关的图片的发布状态均应为未发布,因此,增加根据活动ID修改活动图片的发布状态的方法
            * */
        public bool editPubState(int eid)
        {
            string sqlstr =string.Format( "update dbo.UKNOW_EVENTS_IMAGE set COL_IMAGE_STATE =0 where COL_LANG_ID={0} and COL_EVENTS_ID={1}",(int)this.Language.LanguageType,eid);
            int i= DBHelper.ExecuteNonQuery(sqlstr);
            if (i>0)
            { return true; }
            else
            { return false; }
        }



        //public IList<EventsImageModel> GetPublishedGalleryImageModelsByEventsID(int? eventsID)
        //{
        //    WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
        //    builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_IMAGE_STATE, 1, SearchConditionOperator.Equals));
        //    builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_EVENTS_ID, eventsID, SearchConditionOperator.Equals));
        //    builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));
        //    builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_IMAGE_RECO, 1, SearchConditionOperator.Equals));

        //    string whereClause = builder.ToSqlCommand();
        //    IList<EventsImageModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(Order.PropertyName + "," + UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsImageModel>().ToList();

        //    foreach (EventsImageModel model in models)
        //        SetForeignKeyModel(model);
        //    return models;
        //}

        //public IList<EventsImageModel> GetPublishedGalleryImageModels()
        //{
        //    WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
        //    builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_IMAGE_STATE, 1, SearchConditionOperator.Equals));
        //    builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));
        //    builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_IMAGE_RECO, 1, SearchConditionOperator.Equals));

        //    string whereClause = builder.ToSqlCommand();
        //    IList<EventsImageModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsImageModel>().ToList();

        //    foreach (EventsImageModel model in models)
        //        SetForeignKeyModel(model);
        //    return models;
        //}

        public int GetTotalCountByEventsID(int? eventsID)
        {
            string cmd = string.Format("select count({0}) from {1} where {2}={3} and {4}={5} and {6}={7}",
                COL_IMAGE_ID, TBL_NAME, COL_LANG_ID, (int)this.Language.LanguageType, COL_EVENTS_ID, eventsID, COL_IMAGE_STATE, 1);

            object obj = DBHelper.ExecuteScalar(cmd);
            return (int)obj;
        }

        public ResultInfo Save(EventsImageModel modelInfo)
        {
            if (modelInfo == null) throw new ArgumentNullException("modelInfo");

            ResultInfo result = new ResultInfo(false);

            try
            {
                int rowsAffected = 0;
                if (modelInfo.ID == null)   // insert
                {
                    modelInfo.ID = SqlUtil.GetMaxRecordID(TableName, COL_IMAGE_ID, COL_LANG_ID, (int)this.Language.LanguageType);
                    //modelInfo.State = 0;    // 强制将图片状态置为未发布
                    modelInfo.InsertedTime = DateTime.Now;
                    modelInfo.UpdatedTime = DateTime.Now;
                    rowsAffected = Insert(modelInfo, null);
                }
                else // update
                {
                    modelInfo.UpdatedTime = DateTime.Now;
                    rowsAffected = UpdateByPrimaryKey(modelInfo, null);
                }

                if (rowsAffected > 0)
                {
                    result.Message = "图片数据保存成功！";
                    result.Result = true;
                    result.ReturnObject = modelInfo;
                }
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = string.Format("保存手机图片数据时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo Delete(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);
            using (IDbConnection conn = DBHelper.GetDbConnection())
            {
                conn.Open();
                IDbTransaction trans = conn.BeginTransaction();
                try
                {
                    foreach (int? id in idList)
                        DeleteModelByPrimaryKey(trans, this.GetType(), new KeyValuePair<IField, object>[] { new KeyValuePair<IField, object>(LanguageID, (int)this.Language.LanguageType), new KeyValuePair<IField, object>(this.ID, id) });

                    trans.Commit();
                    result.Result = true;
                    result.Message = "手机图片数据删除成功！";
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    result.Message = string.Format("删除手机图片数据时发生异常。异常信息：{0}", ex.Message);
                }
                finally
                {
                    trans.Dispose();
                }
            }

            return result;
        }

        public ResultInfo DeleteByEventsID(IDbTransaction trans, int? eventsID)
        {
            ResultInfo result = new ResultInfo(false);
            try
            {
                string whereClause = string.Format("where {0}={1} and {2}={3}", COL_LANG_ID, (int)this.Language.LanguageType, COL_EVENTS_ID, eventsID);
                Delete(trans, whereClause);
                result.Result = true;
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Delete, Enums.ActionResult.Success);
            }
            catch (Exception ex)
            {
                result.Exception = ex;
                result.Message = Language.GetAlertMessage(ModelType, Enums.Action.Delete, Enums.ActionResult.Exception, ex);
            }

            return result;
        }

        public ResultInfo Publish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 1;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_IMAGE_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "图片发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("发布图片时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }

        public ResultInfo UnPublish(IList<int?> idList)
        {
            ResultInfo result = new ResultInfo(false);

            IField[] updatedFields = new IField[] { this.State };
            IDataParameter[] parms = DBHelper.GetDataParameters(updatedFields);
            parms[0].Value = 0;

            string ids = "";
            foreach (int? id in idList)
                ids += (ids == string.Empty) ? id.ToString() : "," + id.ToString();

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(InSearchCondition.CreateInstance(COL_IMAGE_ID, DataType.Int, ids));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));

            string whereClause = builder.ToSqlCommand();
            string cmdText = DBHelper.GetUpdateCommandText(this.TableName, updatedFields, whereClause);

            try
            {
                DBHelper.ExecuteNonQuery(cmdText, parms);
                result.Result = true;
                result.Message = "图片取消发布成功！";
            }
            catch (Exception ex)
            {
                result.Message = string.Format("取消发布图片时发生异常。异常信息：{0}", ex.Message);
            }

            return result;
        }
        public IList<EventsImageModel> GetAllPublishedPhoneEventsRecoImageModels()
        {

            WhereClauseBuilder builder = WhereClauseBuilder.CreateInstance(SearchConditionJoinOperator.AND);
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_IMAGE_STATE, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_IMAGE_RECO, 1, SearchConditionOperator.Equals));
            builder.Conditions.Add(CommonSearchCondition.CreateInstance(COL_LANG_ID, (int)this.Language.LanguageType, SearchConditionOperator.Equals));
            string whereClause = builder.ToSqlCommand();
            IList<EventsImageModel> models = GetModels(whereClause, PagingParameterFactory.CreateNonPagingParameter(SortingParameterFactory.CreateInstance(UpdatedTime.PropertyName, SortOrder.Desc))).List.Cast<EventsImageModel>().ToList();

            foreach (EventsImageModel model in models)
                SetForeignKeyModel(model);
            return models;
        }


        #endregion
    }
}
